package com.deyuanyun.pic.ctrl.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.deyuanyun.pic.common.dto.PageJsonBean;
import com.deyuanyun.pic.common.tool.JXL;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.common.util.ajax.AjaxSupport;
import com.deyuanyun.pic.common.util.poi.ExcelUtil;
import com.deyuanyun.pic.common.util.web.Asserts;
import com.deyuanyun.pic.common.util.web.WebUtil;
import com.deyuanyun.pic.ctrl.controller.dto.ExinspOclpointDTO;
import com.deyuanyun.pic.ctrl.controller.dto.ExinspOclpointQueryVO;
import com.deyuanyun.pic.ctrl.controller.dto.RepairTaskDTO;
import com.deyuanyun.pic.ctrl.controller.dto.RepairTaskQueryVO;
import com.deyuanyun.pic.ctrl.domain.CtrlRepairTask;
import com.deyuanyun.pic.ctrl.enumeration.DefectStateEnum;
import com.deyuanyun.pic.ctrl.enumeration.RepairStateEnum;
import com.deyuanyun.pic.ctrl.enumeration.RepairTaskStatedEnum;
import com.deyuanyun.pic.ctrl.service.CoatRepairTaskService;
import com.deyuanyun.pic.pipe.controller.BaseController;
import com.deyuanyun.pic.pipe.service.PipeCenterLineService;
import com.deyuanyun.pic.settings.util.DownExcelUtil;
import com.google.common.base.Predicate;
import com.google.common.collect.Collections2;

/**
 *  涂层维修任务Controller
 *
 * @author ChenKui
 * @date 2016-06-16
 */
@Controller
@RequestMapping("/corrctrl/CoatRepairTask")
public class CoatRepairTaskController extends BaseController{
      
    private @Autowired PipeCenterLineService pipeCenterLineService;//管道中心线
    private @Autowired CoatRepairTaskService coatRepairTaskService;//缺陷任务相关


    //进入维修任务列表页面
    @RequestMapping("/init.html")
    public ModelAndView init(ModelMap model) {
        //维修任务状态
        model.addAttribute("repairTaskStateds", RepairTaskStatedEnum.values());
        //AjaxSupport.sendSuccessText("success", model.asMap());
        return forword("/corrctrl/repair/repairPaint", model);
    }

    //进入创建维修任务页面
    @RequestMapping("/initCreate.html")
    public ModelAndView initCreate(ModelMap model) {
        
        //AjaxSupport.sendSuccessText("success", model.asMap());
        return forword("/corrctrl/repair/repairCreate", model);
    }

    //进入缺陷点详情界面
    @RequestMapping("/initDetail.html")
    public ModelAndView initDetail(ModelMap model) {
        
        //AjaxSupport.sendSuccessText("success", model.asMap());
        return forword("/corrctrl/repair/repairDetails", model);
    }

    /**
     * 查询维修任务列表
     * 
     * @param repairTaskQuery
     * @param model
     */
    @RequestMapping("/queryRepairTaskList.json")
    @ResponseBody
    public void queryRepairTaskList(RepairTaskQueryVO repairTaskQuery,ModelMap model) {
        PageJsonBean jsonBean = new PageJsonBean();
        List<RepairTaskDTO> repairTaskList = coatRepairTaskService.queryRepairTaskList(repairTaskQuery);
        //model.addAttribute("repairTaskList", repairTaskList);
        jsonBean.setList(repairTaskList);
        AjaxSupport.sendSuccessText("success", jsonBean);
        //return forword("/pbf/queryRepairTaskList.jsp", model);
    }

    /**
     * 查询某一任务的详情（含具体缺陷点）
     * 
     * @param repairTaskId
     * @param model
     * @return
     */
    @RequestMapping("/queryDetail.json")
    @ResponseBody
    public void queryDetail(@RequestParam(required = false,value = "repairTaskId") String repairTaskId
            ,@RequestParam(required = false,value = "defectInfoId") String[] defectInfoIds
            ,ModelMap model) {
        
        PageJsonBean jsonBean = new PageJsonBean();
        List<ExinspOclpointDTO> defectInfoList = new ArrayList<ExinspOclpointDTO>();
        if(StringUtils.isNotEmpty(repairTaskId)){
            //查询维修任务的详情信息
            RepairTaskQueryVO repairTaskVO = new RepairTaskQueryVO();
            repairTaskVO.setRepairTaskIds(new String[]{repairTaskId});
            List<RepairTaskDTO> repairTaskList = coatRepairTaskService.queryRepairTaskList(repairTaskVO);
            Asserts.assertTrue(repairTaskList != null && !repairTaskList.isEmpty(), "没有找到对应维修任务记录");
            
            RepairTaskDTO repairTask = repairTaskList.get(0);
            model.addAttribute("repairTask", repairTask);

            //查询维修任务对应的缺陷点
            defectInfoList = coatRepairTaskService.queryDefectInfoList(new String[]{repairTaskId});
            
        }
        
        if(defectInfoIds != null && defectInfoIds.length > 0){
            //包含的缺陷点，为了编辑的时候，方便前端调用。
            ExinspOclpointQueryVO exinspOclpointQueryVO = new ExinspOclpointQueryVO();
            exinspOclpointQueryVO.setDefectInfoId(defectInfoIds);
            Collection<ExinspOclpointDTO> defectList = coatRepairTaskService.queryExinspOclpoint(exinspOclpointQueryVO);
            defectInfoList.addAll(defectList);//加进来
        }
        jsonBean.setList(defectInfoList);
        model.addAttribute("defectInfoList", jsonBean);
        
        AjaxSupport.sendSuccessText("success", model);
        //return forword("/pbf/queryDetail", model);
    }
    
    /**
     * 导出Excel
     * @param repairTask
     * @param model
     * @param response
     * @throws IOException
     */
    @RequestMapping("/toExcel.json")
    @ResponseBody
    public void toExcel(RepairTaskQueryVO repairTask,ModelMap model,HttpServletResponse response) throws IOException {
        
        //查询维修任务的详情信息
        List<RepairTaskDTO> repairTaskList = coatRepairTaskService.queryRepairTaskList(repairTask);
        
        String filePath = "/template/excl/ctrl/repairtask_template.xlsx";
        List<String[]> listSheet = JXL.toListFormVO(repairTaskList, "yyyy-MM-dd");
        Integer beginRow = 3;
        Workbook workbook = ExcelUtil.initWorkbook(filePath, listSheet, beginRow - 2);
        DownExcelUtil.fillWorkbookHead(workbook);
        WebUtil.setDownHeader("涂层维修项目列表" + StringUtils.convertDateToString(new Date(), "yyyyMMdd") + ".xlsx");
        workbook.write(response.getOutputStream());
        
    }

    /**
     * 直接保存
     * 
     * @param repairTask
     * @param defectInfoIds
     */
    @RequestMapping("/createOrUpdate2.json")
    @ResponseBody
    public void createOrUpdate2(CtrlRepairTask repairTask, @RequestParam("defectInfoId") String[] defectInfoIds) {
        
        coatRepairTaskService.createOrUpdate(repairTask, defectInfoIds);
        
        AjaxSupport.sendSuccessText("success", "");
    }
    
    /**
     * 修改维修任务数据状态
     *  用于发布任务任务的情况。
     * repairTaskId=维修任务编号1
     * repairTaskId=维修任务编号2
     * 
     * dataState=state20（可选参数传递，默认就是改成发布状态）
     * 
     * @param repairTaskIds
     * @param dataState
     */
    @RequestMapping("/updateDataState.json")
    @ResponseBody
    public void updateDataState(@RequestParam("repairTaskId") String[] repairTaskIds
            ,@RequestParam(value = "dataState",defaultValue = "state20")DefectStateEnum dataState
            ,ModelMap model) {
        
        int secc = coatRepairTaskService.updateDataStated(repairTaskIds, dataState);
        model.addAttribute("count", repairTaskIds.length);
        model.addAttribute("successCount", secc);
        AjaxSupport.sendSuccessText("success", model);
    }
    

    /**
     * 修改维修任务的修复状态（用于关闭任务）
     * repairTaskId=维修任务编号1
     * repairTaskId=维修任务编号2
     * 
     * repairTaskStated=CLOSED（可选参数，默认就是改为关闭）
     * 
     * @param repairTaskIds
     * @param repairTaskStated
     */
    @RequestMapping("/updateRepairTaskStated.json")
    @ResponseBody
    public void updateRepairTaskStated(@RequestParam("repairTaskId") String[] repairTaskIds
            ,@RequestParam(value = "repairTaskStated",defaultValue = "ALREADY_REPAIR")RepairTaskStatedEnum repairTaskStated
            ,ModelMap model) {
        
        int secc = coatRepairTaskService.updateRepairTaskStated(repairTaskIds, repairTaskStated);
        model.addAttribute("count", repairTaskIds.length);
        model.addAttribute("successCount", secc);
        AjaxSupport.sendSuccessText("success", model);
    }

    /**
     * 删除任务
     * 
     * @param repairTaskIds
     */
    @RequestMapping("/updateToDelete.json")
    @ResponseBody
    public void updateToDelete(@RequestParam("repairTaskId") String[] repairTaskIds,ModelMap model) {
        
        int secc = coatRepairTaskService.updateToDelete(repairTaskIds);
        model.addAttribute("successCount", secc);
        model.addAttribute("count", repairTaskIds.length);
        AjaxSupport.sendSuccessText("success", model);
    }
    
    

    /**
     * 列表数据
     * @param defectSuggestVO
     * @param searchType 目前加这个参数的目的是为了方便前台绑定table的数据，为空的时候按照defectSuggestVO参数查询，为空的时候进行后台查询,不为空直接返回
     */
    @RequestMapping("/queryExinspOclpoint.json")
    @ResponseBody
    public void queryExinspOclpoint(final ExinspOclpointQueryVO defectSuggestVO, @RequestParam(value = "searchType", defaultValue = "") String searchType){

        if(StringUtils.isNotEmpty(searchType)) { //加这个代码的目的是方便前台table控件的数据绑定
            AjaxSupport.sendSuccessText("success", Collections.emptyList());
            return;
        }
        defectSuggestVO.setRepairTaskIdIsNull(true);
        defectSuggestVO.setRepairStateds(new RepairStateEnum[]{RepairStateEnum.WAIT_FOR_REPAIR});
        Collection<ExinspOclpointDTO> defectList = coatRepairTaskService.queryExinspOclpoint(defectSuggestVO);
        if(defectList != null) {
            final List<String> excludeDeIds =  defectSuggestVO.getExcludeDeIds();
            if (excludeDeIds != null && excludeDeIds.size() > 0) {
                //排除页面上不需要展示的缺陷信息,相同管道id和缺陷id才会排除
                defectList = Collections2.filter(defectList, new Predicate<ExinspOclpointDTO>() {
                    @Override
                    public boolean apply(@Nullable ExinspOclpointDTO input) {
                        if(input == null) {
                            return false;
                        }
                        if(excludeDeIds.contains(input.getId()) &&
                                Objects.equals(defectSuggestVO.getPipeId(), input.getPipeLineId())) {
                            return false;
                        } else {
                            return true;
                        }
                    }
                });
            }
        }
        AjaxSupport.sendSuccessText("success", defectList);
    }

}
